// pages/txt/txt.js
const app = getApp();
const url = app.globalData.url;
const WxParse = require('../../wxParse/wxParse.js');  
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loding:true,
    ck:0,
    list:[],
    ewms:false,
    dmyqs:false,
    yqgzs:false,
    value:'',
    pno:1,
    pcont:0,
    jzs: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.peizi();
    this.hqewmxx();
    this.gettglb();
  },
  gettglb(sx){
    let that=this;
    let us=that.data.user,pno=0,ck=that.data.ck,list=[];
    if(sx){
      pno=that.data.pno;
      list=that.data.list;
    }
    that.setData({list:[]})
    let sj={
      uid:ck==0?'':us.uid,
      pno:pno,
      pgs:20
    };
    app.fetch('api/wx/gettgb', sj, "POST", (err, data) => {
      console.log(data)
      for(let p of data.list){
        list.push(p)
      }
      if(data.code==200){
        that.setData({
          pno:data.pno+1,
          list:list,
          pcunt:data.pageCount
        })
      }
      wx.hideLoading()
    })
  },
  phbtn(){
    wx.showLoading({
      title: '获取中...',
    })
    this.setData({ck:0});
    this.gettglb();
  },
  wdyqbtn(){
    wx.showLoading({
      title: '获取中...',
    })
    this.setData({ck:this.data.user.uid});
    this.gettglb();
  },
  trim: function (s) {
    return s.replace(/(^\s*)|(\s*$)/g, "");
  },
  bindinput(e){
    this.setData({value: this.trim(e.detail.value)})
  },
  tijbtn(){
    let that=this;
    let val=that.data.value;
    let us=that.data.user;
    let pz=that.data.peizi;
    let sj={
      uid:val
    };
    if(val!=''&&val!=us.uid){  
      if(val=='0000'){
        wx.showLoading({
          title: '提交中...',
        })
        if (pz.xcxyqyj.brjb.txt > 0) {
          var tt = "写邀请暗号,获得" + pz.xcxyqyj.brjb.txt + "个" + pz.xcx.jb.txt;
          that.czjb(us.uid, 1, pz.xcxyqyj.brjb.txt, tt, "填写邀请暗号获得" + pz.xcx.jb.txt);
        }
        if (pz.xcxyqyj.brmfcs.txt > 0) {
          var mfgm = parseInt(us.mfgm) + parseInt(pz.xcxyqyj.brmfcs.txt);
          that.upuser(us.uid, mfgm);
        }
        that.addtg();
      }else{
        app.fetch('api/wx/user', sj, "GET", (err, data) => {
          console.log(data)
          if (data.code == 200) {
            wx.showLoading({
              title: '提交中...',
            })
          if(pz.xcxyqyj.jljb.txt>0){
            var tt = '好友' +us.nickName+ "填写你的邀请暗号,获得" +pz.xcxyqyj.jljb.txt+"个" +pz.xcx.jb.txt;
            that.czjb(data.data[0].uid, 1,pz.xcxyqyj.jljb.txt, tt, "邀请好友获得");
          }
          if(pz.xcxyqyj.brjb.txt>0){
            var tt = '填写好友' +data.data[0].nickName+ "的邀请暗号,获得" +pz.xcxyqyj.brjb.txt+"个" +pz.xcx.jb.txt;
            that.czjb(us.uid, 1,pz.xcxyqyj.brjb.txt, tt, "填写邀请暗号获得");
          }
          if(pz.xcxyqyj.brmfcs.txt>0){
            var mfgm=parseInt(us.mfgm) + parseInt(pz.xcxyqyj.brmfcs.txt);
            that.upuser(us.uid,mfgm);
          }
          if(pz.xcxyqyj.jlmfcs.txt>0){
            var jlmfcs=parseInt(data.data[0].mfgm) + parseInt(pz.xcxyqyj.jlmfcs.txt);
            that.upuser(data.data[0].uid,jlmfcs);
          }
          that.addtg();
          }else{
            wx.showModal({
              title: '提示',
              content:"code："+data.code+"，msg：" +data.msg,
              success(res){
              }
            })
          } 
        })
      }
    }else{
      wx.showModal({
        title: '提示',
        content:"不能输入自己的邀请暗号",
        success(res){
        }
      })
    } 
  },
  addtg(){
    let that=this;
    app.fetch('api/wx/addtglb',{tguid:that.data.user.uid,uid:that.data.value}, "POST", (err, data) => {
      console.log(data)
      if (data.code == 200) {
        app.fetch('api/wx/upuser',{uid:that.data.user.uid,yquid:that.data.value}, "POST", (err, data) => {
          console.log(data)
          if (data.code == 200) {
            that.hquser();
            wx.hideLoading();
            wx.showToast({
              title: "对接暗号成功",
              icon: 'success',
              duration: 1000
            });
            setTimeout(function () {
              wx.navigateBack({
                data: 1,
                fail(){
                  wx.redirectTo({
                    url: "/pages/index/index"
                  })
                }
              })
            }, 1000)
          }
        })
      }
    })
  },
  czjb(uid,sz, jb, tt, xlx) {
    let that = this;
    let sj = {
      uid:uid,
      sz: sz,
      jb: jb,
      tt: tt,
      lx: 'xcx',
      xlx: xlx ? xlx : ''
    };
    app.fetch('api/wx/czjb', sj, "POST", (err, data) => {
      console.log(data)
      if (data.code == 200) {
        // that.hquser();
      }
    })
  },
  upuser(uid,mfgm) {
    let that = this;
    let sj = {
      uid:uid,
      mfgm: mfgm
    };
    app.fetch('api/wx/upuser', sj, "POST", (err, data) => {
      console.log(data)
      if (data.code == 200) {
        // that.hquser();
      }
    })
  },
  showzd(){
    this.setData({dmyqs:true});
  },
  quxzd(){
    this.setData({dmyqs:false,yqgzs:false});
  },
  ckfxtp: function () {
    // console.log(e.currentTarget.dataset.index);
    wx.canvasToTempFilePath({
      canvasId: 'myCanvas',
      success: function (res) {
        var tempFilePath = res.tempFilePath;
        // var that=this;
        let imgs = [];
        imgs.push(tempFilePath);
        var imgArr = imgs;
        // console.log(imgArr[index]);
        wx.previewImage({
          current: imgArr[0],     //当前图片地址
          urls: imgArr,               //所有要预览的图片的地址集合 数组形式
          success: function (res) { },
          fail: function (res) { },
          complete: function (res) { },
        })
      }
    });
  },
  // 配置文件
  peizi: function () {
    let that = this;
    app.fetch('api/wx/getpeizi', { dlx: 'xcxyqyj' }, "GET", (err, data) => {
      console.log(data)
      if (data.code == 200) {
        wx.setNavigationBarTitle({
          title: data.data.xcxyqyj.title.txt
        });
        data.data.xcxyqyj.tbzp.txt=url+data.data.xcxyqyj.tbzp.txt;
        article_content: WxParse.wxParse('article', 'html', data.data.xcxyqyj.yqgz.txt, that, 0);
        that.setData({ peizi: data.data, loding: false });
        that.hquser();
      } else {
        wx.showModal({
          title: '接口数据错误',
          content: '接口:"' + url + 'api/wx/getpeizi.php' + '",msg:' + data.msg,
          showCancel: false,//是否显示取消按钮
          confirmText: "好的",//默认是“确定”
          confirmColor: 'skyblue',//确定文字的颜色
          success: function (res) {

          },
          fail: function (res) { },//接口调用失败的回调函数
          complete: function (res) { },//接口调用结束的回调函数（调用成功、失败都会执行）
        })
      }
    })
  },
  // 获取user信息;
  hquser() {
    let that = this;
    wx.getStorage({
      key: 'openid',
      success(res) {
        app.fetch('api/wx/user', { openid: res.data,yq:'yq' }, "POST", (err, data) => {
          if (data.code == 200) {
            that.setData({ user: data.data[0] })
            // that.getcsData();
          }else{
            wx.showModal({
              title: '提示',
              content: data.msg,
              success(res){
                if (res.cancel) {
                  //点击取消,默认隐藏弹框
                  // if (options.finish) {
                    wx.navigateBack({ 
                      delta: 1,
                      fail(){
                        wx.redirectTo({
                          url: "/pages/my/my"
                        })
                      }
                     })
                  // }
                } else {
                    wx.redirectTo({
                      url: "/pages/my/my"
                    })
                }
              }
            })
          } 
        })
      },
      fail(){
        wx.showModal({
          title: '提示',
          content: '请先登录',
          success(res){
            if (res.cancel) {
              //点击取消,默认隐藏弹框
              // if (options.finish) {
                wx.navigateBack({ 
                  delta: 1,
                  fail(){
                    wx.redirectTo({
                      url: "/pages/my/my"
                    })
                  }
                 })
              // }
            } else {
                wx.redirectTo({
                  url: "/pages/my/my"
                })
            }
          }
        })
      }
    })
  },
  // 获取二维码
  hqewmxx: function () {
    var that = this;
    app.fetch('api/ewm/ewm', { page: 'pages/txt/txt',dt:'id=100' }, "GET", (err, data) => {
      that.setData({ tgewm: url +"api/ewm/ewm.png"})
    })
  },
  /**
* 先下载头像图片
*/
  getAvaterInfo: function () {
    var that = this;
    this.setData({ ewms: true});
    wx.showLoading({
      title: '下载封面中...',
      mask: true,
    });
    // 二维码
    wx.downloadFile({
      url:url+ that.data.peizi.xcxyqyj.yqhb.txt, //海报图片路径
      success: function (res) {
        wx.hideLoading();
        if (res.statusCode === 200) {
          var avaterSrc = res.tempFilePath; //下载成功返回结果
          that.getQrCode(avaterSrc); //继续下载二维码图片
        } else {
          wx.showToast({
            title: '封面下载失败！',
            icon: 'none',
            duration: 2000,
            success: function () {
              var avaterSrc = "";
              that.getQrCode(avaterSrc);
            }
          })
        }
      }
    })
  },

  /**
   * 下载二维码图片
   */
  getQrCode: function (avaterSrc) {
    wx.showLoading({
      title: '下载二维码...',
      mask: true,
    });
    var that = this;
    wx.downloadFile({
      url: that.data.tgewm, //二维码路径
      success: function (res) {
        wx.hideLoading();
        if (res.statusCode === 200) {
          var codeSrc = res.tempFilePath;
          that.sharePosteCanvas(avaterSrc, codeSrc);
        } else {
          wx.showToast({
            title: '二维码下载失败！',
            icon: 'none',
            duration: 2000,
            success: function () {
              var codeSrc = "";
              that.sharePosteCanvas(avaterSrc, codeSrc);
            }
          })
        }
      }
    })
  },

  /**
   * 开始用canvas绘制分享海报
   * @param avaterSrc 下载的头像图片路径
   * @param codeSrc   下载的二维码图片路径
   */
  sharePosteCanvas: function (avaterSrc, codeSrc) {
    wx.showLoading({
      title: '绘制海报中...',
      mask: true,
    })
    var that = this;
    var cardInfo = {}; //需要绘制的数据集合
    cardInfo.Name = that.data.user.uname ? that.data.user.uname : that.data.user.nickName;
    cardInfo.Anhao = that.data.user.uid;
    cardInfo.Anhaott ="我的暗号";
    const ctx = wx.createCanvasContext('myCanvas'); //创建画布
    var width = "";
    wx.createSelectorQuery().select('#canvas-container').boundingClientRect(function (rect) {
      var height = rect.height;
      var right = rect.right;
      width = rect.width;
      var left = rect.left + 5;
      ctx.setFillStyle('#fff');
      ctx.fillRect(0, 0, rect.width, height);
      var h = rect.height;
      var w = rect.width;
      console.log(rect)
      //头像为正方形
      if (avaterSrc) {
        ctx.drawImage(avaterSrc, 0, 0, width, height);
        ctx.setFontSize(14);
        ctx.setFillStyle('#fff');
        ctx.setTextAlign('left');
      }
      //姓名
      if (cardInfo.Name) {
        ctx.setFontSize(18);
        ctx.setFillStyle('#fff');
        const metrics = ctx.measureText(cardInfo.Name); //测量文本信息
        ctx.fillText(cardInfo.Name, (w / 2) - (metrics.width/2), h/2+30);
        ctx.stroke();
        ctx.rect(((w / 2) - (metrics.width / 2)) - 20, h/2 + 12.5, metrics.width + 40, 25);
        ctx.setFillStyle('rgba(255,255,255,0.4)');
        ctx.fill();
      }
      const anht = ctx.measureText(cardInfo.Anhaott); //测量文本信息
      const anh = ctx.measureText(cardInfo.Anhao); //测量文本信息
      //暗号
      if (cardInfo.Anhaott) {
        ctx.stroke();
        ctx.rect(((w / 2) - ((anht.width + anh.width) / 2)) - 20, h /2 + 35 + 12.5, (anht.width + anh.width) + 40, 25);
        ctx.setFillStyle('rgba(255,255,255,0.4)');
        ctx.fill();
        if (cardInfo.Anhao) {
          ctx.setFontSize(18);
          ctx.setFillStyle('#ff0000');
          ctx.fillText(cardInfo.Anhao, (w / 2) - ((anht.width + anh.width) / 2 - anht.width - 5), h/2 + 30 + 35);
        }
        ctx.setFontSize(15);
        ctx.setFillStyle('#ff0000');
        ctx.fillText(cardInfo.Anhaott, (w / 2) - ((anht.width + anh.width) / 2), h /2 + 30 + 35);
        ctx.fillText(cardInfo.Anhaott, (w / 2) - ((anht.width + anh.width) / 2)+1, h /2 + 30 + 35+1);
        
      }
      
      
      //  绘制二维码
      if (codeSrc) {
        ctx.drawImage(codeSrc, (w /2) - 35, h - 90, 70, 70)
      }

    }).exec()

    setTimeout(function () {
      ctx.draw();
      wx.hideLoading();
    }, 1000)

  },

  /**
   * 多行文字处理，每行显示数量
   * @param text 为传入的文本
   * @param num  为单行显示的字节长度
   */
  textByteLength(text, num) {
    let strLength = 0; // text byte length
    let rows = 1;
    let str = 0;
    let arr = [];
    for (let j = 0; j < text.length; j++) {
      if (text.charCodeAt(j) > 255) {
        strLength += 2;
        if (strLength > rows * num) {
          strLength++;
          arr.push(text.slice(str, j));
          str = j;
          rows++;
        }
      } else {
        strLength++;
        if (strLength > rows * num) {
          arr.push(text.slice(str, j));
          str = j;
          rows++;
        }
      }
    }
    arr.push(text.slice(str, text.length));
    return [strLength, arr, rows] //  [处理文字的总字节长度，每行显示内容的数组，行数]
  },
  clearewm: function () {
    this.setData({ ewms: false });
  },
  //点击保存到相册
  saveShareImg: function () {
    var that = this;
    wx.showLoading({
      title: '正在保存',
      mask: true,
    })
    setTimeout(function () {
      wx.canvasToTempFilePath({
        canvasId: 'myCanvas',
        success: function (res) {
          wx.hideLoading();
          var tempFilePath = res.tempFilePath;
          wx.saveImageToPhotosAlbum({
            filePath: tempFilePath,
            success(res) {
              // utils.aiCardActionRecord(19);
              wx.showModal({
                content: '图片已保存到相册，赶紧发朋友圈晒一下吧',
                showCancel: false,
                confirmText: '好的',
                confirmColor: '#333',
                success: function (res) {
                  if (res.confirm) {
                    that.setData({ ewm: false, dhl: true });
                  }
                },
                fail: function (res) { }
              })
            },
            fail: function (res) {
              wx.showToast({
                title: res.errMsg,
                icon: 'none',
                duration: 2000
              })
            }
          })
        }
      });
    }, 1000);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let that=this;
    let pno=that.data.pno,pcunt=that.data.pcunt;
    if(pno-1<pcunt){
      wx.showLoading({
        title: '获取中...',
      })
      that.gettglb("sx");
    }else{
      that.setData({ jzs:true});
      setTimeout(function () {
        that.setData({ jzs: false });
      }, 1000)
    }
  },
  showyqgz(){
    this.setData({yqgzs:true})
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    let that = this;
    let pz=that.data.peizi;
    let uname=that.data.user.uname ? that.data.user.uname : that.data.user.nickName;
    let title=pz.xcxyqyj.fxbt.txt;
    let lr=pz.xcxyqyj.fxlr.txt;
    title=title.replace(/#uname#/ig, uname);
    console.log(title)
    lr=lr.replace(/#uname#/ig, uname);
    if (res.from === 'button') {

    }
    return {
      title: title,
      path: '/pages/txt/txt',
      imageUrl:url+pz.xcxyqyj.fxtp.txt,
      success: function (res) {
        console.log('成功', res)
      }
    }
  },
  onShareTimeline(){
    let that = this;
    let pz=that.data.peizi;
    let uname=that.data.user.uname ? that.data.user.uname : that.data.user.nickName;
    let title=pz.xcxyqyj.fxbt.txt;
    let lr=pz.xcxyqyj.fxlr.txt;
    title=title.replace(/#uname#/ig, uname);
    console.log(title)
    lr=lr.replace(/#uname#/ig, uname);
    if (res.from === 'button') {

    }
    return {
      title: title,
      query: '/pages/txt/txt',
      imageUrl:url+pz.xcxyqyj.fxtp.txt,
    }
  }
})